package org.visitor.visitorserver.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.visitor.visitorserver.dto.ListWithTotal;
import org.visitor.visitorserver.dto.ProfessorDtoType1;
import org.visitor.visitorserver.dto.ProfessorDtoType2;
import org.visitor.visitorserver.dto.ProfessorDtoType3;
import org.visitor.visitorserver.entity.Professor;
import org.visitor.visitorserver.mapper.ProfessorMapper;
import org.visitor.visitorserver.service.ProfessorServiceInter;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.sql.Date;
import java.util.*;

@Service
public class ProfessorServiceImpl implements ProfessorServiceInter {
    @Autowired
    private ProfessorMapper professorMapper;

    /**
     * PC端通过姓名分页获取专家
     * @param requestBody
     * @return
     */
    @Override
    public ListWithTotal getProfessorList(Map<String, String> requestBody) {
        ListWithTotal listWithTotal = new ListWithTotal();

        String pageNumStr = requestBody.get("pageNum");
        if (pageNumStr == null || pageNumStr.isEmpty()) {
            throw new RuntimeException("页码不能为空");
        }
        int pageNum = Integer.parseInt(pageNumStr);

        String pageSizeStr = requestBody.get("pageSize");
        if (pageSizeStr == null || pageSizeStr.isEmpty()) {
            throw new RuntimeException("每页条数不能为空");
        }
        int pageSize = Integer.parseInt(pageSizeStr);

        Page<Professor> page = new Page<>(pageNum, pageSize);

        // 构建查询条件
        LambdaQueryWrapper<Professor> queryWrapper = new LambdaQueryWrapper<>();
        String name = requestBody.get("name");
        if (name != null && !name.isEmpty()) {
            // 假设根据 name 字段进行模糊查询，可根据实际需求修改
            queryWrapper.like(Professor::getName, name);
        }

        String branchName = requestBody.get("branchName");
        if (branchName != null && !branchName.isEmpty()) {
            // 假设根据 branchName 字段进行模糊查询，可根据实际需求修改
            queryWrapper.like(Professor::getBranchName, branchName);
        }

        // 执行分页查询
        IPage<Professor> pageResult = professorMapper.selectPage(page, queryWrapper);
        int total = (int) pageResult.getTotal(); // 满足查询条件的数据总数
        List<Professor> list = pageResult.getRecords();

        listWithTotal.setTotal(total);
        listWithTotal.setList(list);
        return listWithTotal;
    }

    /**
     * PC端新增专家
     * @param requestBody
     * @return
     */
    @Override
    public int insertOneProfessor(Map<String, String> requestBody) {
        Professor professor = new Professor();
        professor.setName(requestBody.get("name")); // 参数
        professor.setArea(requestBody.get("area")); // 参数
        professor.setTel(requestBody.get("tel")); // 参数
        professor.setBranchName(requestBody.get("branchName")); // 参数
        professor.setIsCheck(requestBody.get("isCheck")); // 参数
        professor.setZw(requestBody.get("zw")); // 参数
        professor.setStatus(requestBody.get("status")); // 参数

        String price = requestBody.get("price");
        if (price == null || price.isEmpty()) {
            throw new RuntimeException("专家的价格不能为空");
        }
        professor.setPrice(Integer.parseInt(price)); // 参数

        // 初始化值
        professor.setId(UUID.randomUUID().toString());
        professor.setAppointmentNumber(0); // 初始化为0
        professor.setSource(1); // 初始化为手动添加
        professor.setRate(0);
        professor.setIsDel(0);
        professor.setSort(0);
        professor.setCreateAt(new Date(new java.util.Date().getTime()));
        professor.setUpdateAt(new Date(new java.util.Date().getTime()));

        // 数据存入数据库前验证
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        Validator validator = factory.getValidator();
        Set<ConstraintViolation<Professor>> violations = validator.validate(professor);

        if (!violations.isEmpty()) {
            System.out.println(violations.iterator().next().getMessage());
            throw new RuntimeException(violations.iterator().next().getMessage());
        }

        int rows = professorMapper.insert(professor);
        if (rows <= 0) {
            throw new RuntimeException("专家添加失败");
        }

        return rows;
    }

    /**
     * PC端删除专家
     * @param requestBody
     * @return
     */
    @Override
    public int deleteOneProfessor(Map<String, String> requestBody) {
        String id = requestBody.get("id");
        if (id.isEmpty()) {
            throw new RuntimeException("未知的要删除的专家");
        }
        int rows = professorMapper.deleteById(id);
        if (rows <= 0) {
            throw new RuntimeException("专家删除失败");
        }
        return rows;
    }

    /**
     * PC端修改专家
     * @param requestBody
     * @return
     */
    @Override
    public int updateOneProfessor(Map<String, String> requestBody) {
        String id = requestBody.get("id");
        if (id == null || id.isEmpty()) {
            throw new RuntimeException("未知的要更新的专家");
        }

        LambdaUpdateWrapper<Professor> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Professor::getId, id);

        // 根据 requestBody 中的字段动态设置更新条件
        requestBody.forEach((key, value) -> {
            if (value != null && !value.isEmpty()) {
                switch (key) {
                    case "name":
                        updateWrapper.set(Professor::getName, value);
                        break;
                    case "area":
                        updateWrapper.set(Professor::getArea, value);
                        break;
                    case "tel":
                        updateWrapper.set(Professor::getTel, value);
                        break;
                    case "isCheck":
                        updateWrapper.set(Professor::getIsCheck, value);
                        break;
                    case "zw":
                        updateWrapper.set(Professor::getZw, value);
                        break;
                    case "status":
                        updateWrapper.set(Professor::getStatus, value);
                        break;
                    default:
                        break;
                }
            }
        });

        // 设置更新时间
        updateWrapper.set(Professor::getUpdateAt, new Date(new java.util.Date().getTime()));

        int rows = professorMapper.update(null, updateWrapper);
        System.out.println(rows);
        if (rows <= 0) {
            throw new RuntimeException("专家更新失败");
        }
        return rows;
    }

    /**
     * (手机端)通过名字获取专家列表
     * @param requestBody
     */
    @Override
    public List<ProfessorDtoType1> getProfessorNameList(Map<String, String> requestBody) {
        String name = requestBody.get("name");
        LambdaQueryWrapper<Professor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (name != null && !name.isEmpty()) {
            lambdaQueryWrapper.like(Professor::getName, name);
        }
        lambdaQueryWrapper.select(Professor::getId, Professor::getArea, Professor::getName, Professor::getBranchName);
        List<Professor> list = professorMapper.selectList(lambdaQueryWrapper);

        List<ProfessorDtoType1> pdt1 = new ArrayList<>();
        list.forEach((item) -> {
            ProfessorDtoType1 dto = new ProfessorDtoType1();
            dto.setId(item.getId());
            dto.setName(item.getName());
            dto.setArea(item.getArea());
            dto.setBranchName(item.getBranchName());
            pdt1.add(dto);
        });
        return pdt1;
    }

    /**
     * (手机端)获取专家列表top3
     * @param requestBody
     * @return
     */
    @Override
    public List<ProfessorDtoType2> getProfessorTop3List(Map<String, String> requestBody) {
        String name = requestBody.get("name");
        LambdaQueryWrapper<Professor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (name != null && !name.isEmpty()) {
            lambdaQueryWrapper.like(Professor::getName, name);
        }
        lambdaQueryWrapper.orderByDesc(Professor::getRate);
        lambdaQueryWrapper.like(Professor::getName, name);
        lambdaQueryWrapper.select(Professor::getId, Professor::getArea, Professor::getName);
        List<Professor> list = professorMapper.selectList(lambdaQueryWrapper);

        // 截取列表的前三项
        if (list.size() > 3) {
            list = list.subList(0, 3);
        }

        List<ProfessorDtoType2> pdt2 = new ArrayList<>();
        list.forEach((item) -> {
            ProfessorDtoType2 dto = new ProfessorDtoType2();
            dto.setId(item.getId());
            dto.setName(item.getName());
            dto.setArea(item.getArea());
            pdt2.add(dto);
        });
        return pdt2;
    }

    /**
     * (手机端)获取专家列表top10
     * @param requestBody
     * @return
     */
    @Override
    public List<ProfessorDtoType3> getProfessorTop10List(Map<String, String> requestBody) {
        String name = requestBody.get("name");
        LambdaQueryWrapper<Professor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (name != null && !name.isEmpty()) {
            lambdaQueryWrapper.like(Professor::getName, name);
        }
        lambdaQueryWrapper.orderByDesc(Professor::getRate);
        lambdaQueryWrapper.like(Professor::getName, name);
        lambdaQueryWrapper.select(Professor::getId, Professor::getArea, Professor::getName, Professor::getPrice, Professor::getRate);
        List<Professor> list = professorMapper.selectList(lambdaQueryWrapper);

        // 截取列表的前10项
        if (list.size() > 10) {
            list = list.subList(0, 10);
        }

        List<ProfessorDtoType3> pdt3 = new ArrayList<>();
        list.forEach((item) -> {
            ProfessorDtoType3 dto = new ProfessorDtoType3();
            dto.setId(item.getId());
            dto.setName(item.getName());
            dto.setArea(item.getArea());
            dto.setPrice(item.getPrice());
            dto.setRate(item.getRate());
            pdt3.add(dto);
        });
        return pdt3;
    }

    @Override
    public Professor roleConfirm(Map<String, String> requestBody) {
        String mobile = requestBody.get("mobile"); // 获取手机号查询对应专家
        LambdaQueryWrapper<Professor> lqw = new LambdaQueryWrapper<>();

        if (mobile == null || mobile.isEmpty()) {
            throw new RuntimeException("专家手机号未输入");
        }
        lqw.eq(Professor::getTel, mobile);
        Professor professor = professorMapper.selectOne(lqw);
        if (professor == null) {
            throw new RuntimeException("未查询到对应专家");
        }
        return professor;
    }
}
